// packageShop/pages/goodsInfo/goodsInfo.js
var configUrl = require('../../../config/config') //引入配置接口文件
var util = require('../../../utils/util') //引入配置接口文件
import { spellApi } from '../../../config/config'
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    defaultAddr:{},//定位地址
    temporaryAddressData:undefined,//选择地址
    footprintGuid: '', //足迹全局id
    recomandShop:{},//推荐门店
    showRecomandShop:false,
    reGuid: false, //是否onshow判断是否重新生成的guid
    CustomBar: app.globalData.CustomBar,
    statusHeight: app.globalData.StatusBar,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    tableIsHidden: true,
    scrollTop: 0,
    showNotWifiPaly: false,
    fontText: 1,
    goodsImgText: 1,
    showOtherAddr: false,
    contPage: 0,
    shareModal: true,
    swiperTyle: false,
    PlayTyle: false,
    screenSku: [], //已选SKU
    slectNum: 0, //已选项数
    buyGoodsNum: 1,
    carGoods: 0, //购物车数
    thenSlect: 0,
    swiperList: [],
    selectIndex: 0,
    /**-合伙人--*/
    isShowPartnerAll: true,
    showPartnerCodePop: false,
    mainimgUrl: '', // 商品主图
    /**定价购买文案 */
    depositBuyDescription: '',
    popupOpen: '' ,// 进入属性弹框不同入口
    spellVerDlg: false, // 拼团校验弹框
    spellList: [],
    timer: "",                                                     // 倒计时定时器名称
    operBtnShow: false,
    authorizationPopup: false,
    locationData: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad: function (options) {
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    this.setData({
      footprintGuid: util.guid(),
      reGuid: false
    })
    var that = this
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    })
    if (!wx.getStorageSync('addrCode').provinceCode) {
      app.getUserLocation() //初始化获取定位地址
    }
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    wx.getSetting({
      success(res) {
        //这里判断是否有定位权限
        if (!res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocation'] == false) {
          that.setData({
            locationData : true
          })
        } else {
          that.setData({
            locationData : false
          })
        }
      }
    })
    that.setData({
      defaultAddr : wx.getStorageSync('addrCode')
    })
    var parms = {
      areaCode: wx.getStorageSync('addrCode').provinceCode
    }
    if (options.scene || options.hid) {
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      if (options.scene) {
        app.getShareCode(scene, (res) => {
          this.setData({
            skuId: res.skuId
          })
          parms.skuId = res.skuId
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('getLocation') === 'N') {
              that.setData({
                showSetting: true
              })
            }
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              that.setData({
                showSetting: false
              })
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
              }
              app.bindingPartner(res.userId)
              this.getGoodInfoHeader(parms) //调用获取商品详情
              console.log('调用获取商品详情1')
              this.getGoodsImgText(parms.skuId) //调用获取商品详情-图文详情
              this.getCoupon(parms.skuId) //获取商品优惠券
              this.recommendGoodsList(parms) //猜你喜欢列表
              this.getShippingAddress() //获取收货地址
              this.getCarGoodsNumber() //获取购物车商品数
            }
          }, 500)

        })
      } else if (options.hid) {
        var shareData={userId:options.hid}
        wx.setStorageSync('shearData', shareData)
        that.setData({
          skuId: options.skuId
        })
        parms.skuId = options.skuId
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('getLocation') === 'N') {
            that.setData({
              showSetting: true
            })
          }
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            that.setData({
              showSetting: false
            })
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                } else {
                  callback(true)  //低版本微信绑过电话视为已登录
                }
              }
              // this.setData({
              //   isShowGetUserInfo: true
              // })
            }
            app.bindingPartner(options.hid)
            
            that.getGoodsImgText(parms.skuId) //调用获取商品详情-图文详情
            that.getCoupon(parms.skuId) //获取商品优惠券
            that.recommendGoodsList(parms) //猜你喜欢列表
            that.getShippingAddress() //获取收货地址
            that.getCarGoodsNumber() //获取购物车商品数
            
            that.getGoodInfoHeader(parms) //调用获取商品详情
            console.log('调用获取商品详情2')

          }
        }, 500)
      }
    } else {
      this.setData({
        skuId: options.id
      })
      parms.skuId = options.id
      this.getGoodInfoHeader(parms) //调用获取商品详情
      console.log('调用获取商品详情3')
      this.getGoodsImgText(parms.skuId) //调用获取商品详情-图文详情
      this.getCoupon(parms.skuId) //获取商品优惠券
      this.recommendGoodsList(parms) //猜你喜欢列表
      this.getShippingAddress() //获取收货地址
      this.getCarGoodsNumber() //获取购物车商品数
      if (options.spellGroupId) {
        this.selectModel('', 'goSpell', options.spellGroupId,'buy-Experience','1')
      }
    }
    let depositBuyDescriptionList = app.globalData.getListvalue(app.globalData.valLsit, 'DEPOSIT_PARAM')
    if (depositBuyDescriptionList && depositBuyDescriptionList.length > 0) {
      that.setData({
        depositBuyDescription : depositBuyDescriptionList[0].name
      })
    }
    wx.removeStorageSync('temporaryAddressData')
  },
//   getTimedata(time){
// 　　var nowTime = +new Date();  //返回的是当前时间的毫秒数
// 　　var inputTime = +new Date(time); //返回的是输入的毫秒数
// 　　var times = (inputTime - nowTime)/1000;  //times是剩余时间转换成秒
// 　　　　var days = parseInt(times/60/60/24) //声明变量存储天数
// 　　　　　　days = days<10?'0'+days:days;
// 　　　　var hours = parseInt(times/60/60%24) //声明变量存储小时
// 　　　　　　hours = hours<10?'0'+hours:hours;
// 　　　　var mins = parseInt(times/60%60) //声明变量存储分钟
// 　　　　　　mins = mins<10?'0'+mins:mins;
// 　　　　var Scons = parseInt(times%60) //生命便令存储当前的秒
// 　　　　　　Scons = Scons<10?'0'+Scons:Scons;

// 　　　　return '距离还有'+days+'天'+hours+'时'+mins+'分'+Scons+'秒';
  
//   },
  getContPage: function (e) { //获取图片索引
    if (e.detail.current != 0) {
      this.stopPalyVideo()
      this.setData({
        swiperTyle: true
      })
    } else {
      this.setData({
        PlayTyle: false,
        swiperTyle: false
      })
    }
    this.setData({
      contPage: e.detail.current,
    })
  },
  showAndHiddenImg: function (e) { //播放状态交互
    if (e.detail.current != 0) {
      this.setData({
        PlayTyle: true,
      })
    } else {
      this.setData({
        PlayTyle: false,
      })
    }
  },
  goEvaluateList(e) { //评价
    wx.navigateTo({
      url: '/packageShop/pages/goodsEvaluate/goodsEvaluate',
    })
  },
  goreBack: function (e) { //返回
    wx.navigateBack({
      delta: 1
    })
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  formatDate(date) {
    var timestamp = new Date(date.replace(/-/g, "/")).getTime(new Date(date.replace(/-/g, "/")))
    var date = new Date(timestamp);
    var y = 1900 + date.getYear();
    var m = "0" + (date.getMonth() + 1);
    var d = "0" + date.getDate();
    var hh = "0" + (date.getHours());
    var mm = "0" + (date.getMinutes());
    return m.substring(m.length - 2, m.length) + "月" + d.substring(d.length - 2, d.length) + "日" + hh.substring(hh.length - 2, hh.length) + ":" + mm.substring(mm.length - 2, mm.length);
  },
  // 进入导购推荐门店列表
  goRecommendStores(e){
    wx.navigateTo({
      url: '/packageShop/pages/nearbyStores/nearbyStores?detail=share',
    })
  },
    /**
   * 设置弹窗-继续浏览
   */
  continueView: function () {
    wx.setStorageSync('showSetting', false)
    this.setData({showSetting: false})
},
  goNearbyStores(e) { //附近门店
    let that = this
    wx.getSetting({
      success(res) {
        //这里判断是否有定位权限
        if (!res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocation'] == false) {
          app.getRealLocation(resp => {
            if (resp && resp.showSetting == true) {
              that.setData({showSetting: true})
            }
          })
        } else {
          var defaultLocation = wx.getStorageSync('addrCode')  //定位地址
          var temporaryAddressData =this.data.temporaryAddressData //选择地址
          if (temporaryAddressData&&temporaryAddressData.provinceCode) {
            var address = temporaryAddressData.province + temporaryAddressData.city + temporaryAddressData.region
            var showaddress = temporaryAddressData.province  + temporaryAddressData.city  + temporaryAddressData.region
            if (temporaryAddressData.street) {
              address += temporaryAddressData.street
              showaddress += (temporaryAddressData.street)
            }
            var addData = {
              data: address,
              showdata: showaddress
            }
            wx.setStorageSync('looknearbyStores', addData)
          } else {
            var address = defaultLocation.province + defaultLocation.city + defaultLocation.district
            var showaddress = defaultLocation.province + defaultLocation.city + defaultLocation.district
            if (defaultLocation.townName) {
              address += (defaultLocation.townName+defaultLocation.street+defaultLocation.streetNumber)
              showaddress += ( defaultLocation.townName)
            }
            var addData = {
              data: address,
              showdata: showaddress
            }
            wx.setStorageSync('looknearbyStores', addData)
          }
          wx.navigateTo({
            url: '/packageShop/pages/nearbyStores/nearbyStores?detail=nearBy',
          })
        }
      }
    })
  },
  selectLookInfo: function (e) { //选择查看图文 or 规格参数
    var type = e.currentTarget.dataset.val
    if (type == 1) {
      this.setData({
        goodsImgText: 1
      })
    } else {
      this.setData({
        goodsImgText: 2
      })
    }
  },
  lookImgS: function (e) { //图片预览
    var that = this;
    var src = e.currentTarget.dataset.src;
    var imgList = that.data.swiperList;
    var list = []
    for (let val of imgList) {
      if (val.type == 'image') {
        list.push(util.getImgUrl(val.picUrl))
      }
    }
    wx.previewImage({
      current: util.getImgUrl(src), // 当前显示图片
      urls: list // 需要预览的图片列表
    })
  },
 async getGoodInfoHeader(parms) { //获取商品详情头部数据
    var that = this;
    parms.viewFlag = true
    parms.uuid = that.data.footprintGuid

    let defaultAddr = wx.getStorageSync('addrCode')
    let temporaryAddressData = that.data.temporaryAddressData
    console.log('请求头参数哈哈temporaryAddressData',temporaryAddressData)
    console.log('请求头参数哈哈defaultAddr',defaultAddr)
    let province= temporaryAddressData?temporaryAddressData.provincCode:(defaultAddr&&defaultAddr.provinceCode)
    let city=temporaryAddressData?temporaryAddressData.cityCode:(defaultAddr&&defaultAddr.cityCode)
    let region=temporaryAddressData?temporaryAddressData.regionCode:(defaultAddr&&defaultAddr.districtCode)
    let street= temporaryAddressData?temporaryAddressData.streetCode:(defaultAddr&&defaultAddr.townCode||'')
    let pricePstCode = await this.searchSaleRegion({ province,  city,  region,  street  })
    let headers = {
      "Content-Type": "application/json;charset=UTF-8",
      'token': wx.getStorageSync('loginMsg').token,    //请求token
      'firstAccessServerTime': wx.getStorageSync('firstAccessServerTime'),   //当次打开小程序的时间(小程序完全关闭为一次)
      'pricePstCode':pricePstCode,
      'cityCode':city,
      'provinceCode':province,
      'addrCode':province+','+city+','+region+(street?(','+street):'')
    }
    console.log('请求参数headers',headers)
    app.reqFun.requestJson('get', configUrl.getGoodsInfoHead, parms, (res) => {
      if (res.data.success) {
        var data = res.data.data
        var swiperList = []
        if (data.mainVideo) {
          that.setData({
            isNotVideo: false,
            mainimgUrl: data.pics[0].picUrl
          })
          var videoJson = {
            id: 0,
            type: 'video',
            url: data.mainVideo,
            imgUrl: data.pics[0].picUrl
          }
          swiperList.push(videoJson)
        } else {
          that.setData({
            isNotVideo: true
          })
        }
        for (let val of data.pics) {
          val.type = 'image'
          swiperList.push(val)
        }
        if (data.type == 2 && data.isSeckill == 1) { //是否参与秒杀活动
          that.getReturnTime(data.endTime)
        }
        if (data.startTime) {
          data.newStartTime = that.formatDate(data.startTime)
        }
        that.setData({
          swiperList: swiperList,
          goodsInfoData: data,
          operBtnShow: true
        })
        var inventoryNum = 0
        for (let sku of data.skus) {
          inventoryNum = sku.inventory + inventoryNum
          if (sku.id == that.data.skuId) {
            // if(sku.id==1106){
            that.setData({
              SelectedSku: sku
            })
            if (sku.inventory > 0) { //有库存并且有销售区域
              that.getIsGoodsNum(sku) //请求是否有货（未完成）
            } else if (sku.inventory == 0) { //如果没有库存
              that.setData({
                isGoods: '无货'
              })
            }
            this.getSkuSpecName(sku.productId) //调用获取SKU集合
          }
        }
        that.setData({
          inventoryNum: inventoryNum,
        })
      } else {
        wx.showToast({
          title: '获取商品信息失败:' + res.data.msg,
          icon: 'none'
        })
      }
    },'',headers)
  },
  getReturnTime(time) { //处理活动倒计时--time=活动结束时间
    let that = this;
        that.setData({
          timer: setInterval(function(){
             var lefttime = parseInt((new Date(time.replace(/-/g,"/")).getTime() - new Date().getTime()));
             if(lefttime <= 0) {
               that.setData({
                returnTime:{day:"00",hours:"00",minute:"00",second:"00"}
               })
               clearInterval(that.data.timer);
               return;
             }
  
             var d = parseInt(lefttime /1000 /3600 /24);  //天数
             var h = parseInt(lefttime / 1000 / 3600 % 24); //小时
             var m = parseInt(lefttime / 1000 / 60 % 60);    //分钟
             var s = parseInt(lefttime / 1000  % 60);        //当前的秒
  
             d < 10 ? d = "0" + d : d;
             h < 10 ? h = "0" + h : h;
             m < 10 ? m = "0" + m : m;
             s < 10 ? s = "0" + s : s;
  
             that.setData({
              returnTime:{ day: d, hours: h, minute: m, second:s }
             })
          },1000)
        })
  },
  getIsGoodsNum(sku) { //请求获取当前SKU是否在销售区域内
    console.log('重新匹配附近门店')
    var that = this;
    var parms = {
      skuProductId: sku.id
    }
    var isDefaultLocation = wx.getStorageSync('addrCode')
    var temporaryAddressData =that.data.temporaryAddressData
    if (temporaryAddressData) {
      var address = temporaryAddressData.province + temporaryAddressData.city + temporaryAddressData.region
      var codes = temporaryAddressData.provinceCode + "," + temporaryAddressData.cityCode + "," + temporaryAddressData.regionCode
      if (temporaryAddressData.street) {
        codes += ("," + temporaryAddressData.streetCode)
        address += temporaryAddressData.street
      }
      parms.pstAreaCodes = codes
      that.getnearby(address)
      that.setData({
        goShopAddr: address
      })
    } else {
      var codes = isDefaultLocation.provinceCode + "," + isDefaultLocation.cityCode + "," + isDefaultLocation.districtCode + "," + isDefaultLocation.townCode
      var address = isDefaultLocation.province + isDefaultLocation.city + isDefaultLocation.district + isDefaultLocation.townName
      parms.pstAreaCodes = codes
      that.getnearby(address+isDefaultLocation.street+isDefaultLocation.streetNumber)
      that.setData({
        goShopAddr: address
      })
    }
    parms.shopId = that.data.goodsInfoData.shopId
    app.reqFun.requestJson('post', configUrl.validByAreaCode, parms, (res) => {
      if (res.data.success) {
        var isGoods = ''
        if (res.data.data) {
          isGoods = '有货'
        } else {
          isGoods = '不在销售区域内'
        }
        that.setData({
          isGoods: isGoods
        })
      }
    }, true)
  },
  getnearby(data) { //获取附近门店
    var that = this;
    var parms = {
      address: data
    }
    // 地址换取经纬度
    app.reqFun.requestJson('get', configUrl.geocode, parms, (res) => {
      if (res.data.success) {
        const params={
          distance: 100000,
          latitude: res.data.data.latitude,
          longitude:  res.data.data.longitude
        }
        //经纬度获取附近门店   distance范围 latitude纬度   longitude 经度
        app.reqFun.requestJson('get', configUrl.nearbyShop, params, (res) => {
          if (res.data.success&&res.data.data.length>0) {
            that.setData({
              nowShowNearby: res.data.data[0],
              nowShowNearbyList: res.data.data
            })
          } else {
            that.setData({
              nowShowNearby: '',
              nowShowNearbyList: []
            })
          }
        }, true)
      }
    })
  },
  getSkuSpecName(productId) { //获取该sku父级商品下所有的sku   触发条件（在线购买，已选点击选择）
    var that = this;
    var SelectedSku = JSON.parse(that.data.SelectedSku.skuSpecs)
    app.reqFun.requestJson('get', configUrl.getGoodsSkus + productId, '', (res) => {
      if (res.data.success ) {
        var data = res.data.data
        for (let val of SelectedSku) {
          for (let attr of data) {
            for (let ava of attr.specs) {
              if (ava.productAttrItemId == val.value || ava.value == val.value) {
                ava.isCheck = true
              }
            }
          }
        }
        that.setData({
          skuSelectBoxData: data
        })

        that.matchingSku(data)
      }
    }, true)
  },
  getGoodsImgText(skuId) { //获取商品详情 - 图文详情
    var that = this;
    var parms = {
      showPlatform: 'mobile'
    }
    app.reqFun.requestJson('get', configUrl.getGoodsImgText + skuId, parms, (res) => {
      if (res.data.success) {
        var data = res.data.data
        var content = ""
        for (let val of data.texts) {
          if (val.content) {
            content += val.content
          }
        }

        if (content.indexOf('<img') >= 0) {
          var newContStr = content.replace(/<img/g, "<img style='width:100%;height:auto;'").replace(/http:\/\//g, 'https://')

          content = newContStr
        }
        that.setData({
          contentInfo: content,
          Specifications: data.values
        })
      }
    })
  },
  getShippingAddress() { //获取收货地址
    console.log('哈哈哈啊哈获取收货地址')
    var that = this;
    var parms = {
      pageFlag: false
    }
    app.reqFun.requestForm('post', configUrl.addressList, parms, (res) => {
      if (res.data.success ) {
        if (res.data.data) {
          var list = res.data.data.records
          that.setData({
            addressListData: list //收货地址data
          })
          var defaultAddr=wx.getStorageSync('addrCode')//定位地址
          let temporaryAddressData = that.data.temporaryAddressData//选择地址
          let data={}
          if(temporaryAddressData&&temporaryAddressData.provinceCode){
            data = temporaryAddressData.province + temporaryAddressData.city + temporaryAddressData.region + temporaryAddressData.street
          }else{
            data = defaultAddr.province + defaultAddr.city + defaultAddr.district + defaultAddr.townName+defaultAddr.street+defaultAddr.streetNumber
          }
          that.getnearby(data)
        } else   that.setData({  addressListData: [] })//收货地址data   }
      } else {
        wx.showToast({
          title: '查询地址失败：' + res.data.msg,
          icon: 'none'
        })
      }
    }, true)
  },
  searchSaleRegion(addrList){
    return new Promise((resolve,reject)=>{
      app.reqFun.requestJson('post',configUrl.getPricePstCode,addrList,(res)=>{
        if(res.data.success){
          resolve (res.data.msg)
        }else{
          resolve ('9999999')//没有查询到价格区域
        }
      })
  })
   },
  async slectAddressData(e) { //  选择收货地址列表中的地址
    // wx.setStorageSync('temporaryAddressData', e.currentTarget.dataset.val)
    var data = e.currentTarget.dataset.val
    console.log('data', data)
    wx.setStorageSync('selectAddId', data.id)
    wx.removeStorageSync('temporaryAddressData')
    var datas = this.data.addressListData
    var isHaveAddress
    for (let val of datas) {
      val.isChecked = false
      if (val.id == data.id) {
        val.isChecked = true
        isHaveAddress ={
          province:val.provinceName,
          provinceCode:val.province,
          city:val.cityName,
          cityCode:val.city,
          region:val.regionName,
          regionCode:val.region,
          street:val.streetName,
          streetCode:val.street
        } 
      }
      this.setData({
        addressListData: datas,
        temporaryAddressData: isHaveAddress,
        modelPopup: '',
        locationData: false
      })
      this.getUpdateGoodInfo(this.data.skuId)
    }
  },
  selectOhterAddr(e) { //选择其他收货地址
    this.setData({
      showOtherAddr: true,
      sprovince: '',
      scity: '',
      sregion: '',
      sstreet: '',
      goshoptype: e.currentTarget.dataset.goshoptype
    })
    this.getAddressSelectData()
  },
  restSelect(e) { //重新选择
    if (e.currentTarget.dataset.val == 2) {
      this.setData({
        sprovince: '',
        scity: '',
        sregion: '',
        sstreet: ''
      })
      this.getAddressSelectData()
    } else if (e.currentTarget.dataset.val == 3) {
      this.setData({
        scity: '',
        sregion: '',
        sstreet: ''
      })
      this.getAddressSelectData(e.currentTarget.dataset.item, true)
    } else if (e.currentTarget.dataset.val == 4) {
      this.setData({
        sregion: '',
        sstreet: ''
      })
      this.getAddressSelectData(e.currentTarget.dataset.item, true)
    }
  },
  getAddressSelectData(e, aa) { //查询4级地址数据
    var that = this;
    var parms = {
      parentCode: 100000000000
    }
    var data = ""
    if (e) {
      if (aa) {
        data = e
      } else {
        data = e.currentTarget.dataset.val
      }
      parms.parentCode = data.code
      if (data.areaLevel == 2) {
        that.setData({
          sprovince: data
        })
      } else if (data.areaLevel == 3) {
        that.setData({
          scity: data
        })
      } else if (data.areaLevel == 4) {
        that.setData({
          sregion: data
        })
      } else if (data.areaLevel == 5) {
        that.setData({
          sstreet: data
        })
      }
    }
    // 待选省市区列表获取
    app.reqFun.requestJson('get', configUrl.listByParentCode, parms, (res) => {
      if (res.data.success) {
        if (res.data.data.length > 0) {
          that.setData({
            itemsAddr: res.data.data,
          })
        } else {
          if (that.data.goshoptype == 'goshoptype') { //到店选择其他地址触发
            that.setData({
              showOtherAddr: false
            })
            that.goSelsctShop();
          } else {
            that.setData({ //关闭弹窗
              modelPopup: '',
              showOtherAddr: false
            })
          }

          var temporaryAddressData = {
            province:that.data.sprovince.name,
            provinceCode:that.data.sprovince.code,
            city:that.data.scity.name,
            cityCode:that.data.scity.code,
            region:that.data.sregion.name,
            regionCode:that.data.sregion.code,
            street:that.data.sstreet.name||'',
            streetCode:that.data.sstreet.code||''
          }
          that.setData({
            temporaryAddressData: temporaryAddressData,
            locationData: false
          })
          wx.setStorageSync('temporaryAddressData', temporaryAddressData)
          wx.removeStorageSync('selectAddId')
          this.getGoodInfoHeader({
            // areaCode: that.data.sprovince.code,
            skuId: that.data.SelectedSku.id,
            uuid: that.data.footprintGuid
          })
          console.log('调用获取商品详情4')
          that.getIsGoodsNum({
            id: that.data.skuId
          })


        }
      } else {
        wx.showToast({
          title: '查询地址失败：' + res.data.msg,
          icon: 'none'
        })
      }
    }, true)
  },
  recommendGoodsList(parms) { //为您推荐
    var that = this;
    app.reqFun.requestJson('get', configUrl.recommendGoodsList, parms, (res) => {
      if (res.data.success) {

        // that.setData({
        //       recommendGoodsListData:res.data.data,   //为您推荐data
        //     })

        if (res.data.data) {
          var data = res.data.data
          var result = [];
          for (var i = 0; i < data.length; i += 3) {
            result.push(data.slice(i, i + 3));
          }
          that.setData({
            recommendGoodsListData: result, //为您推荐data
          })
        } else {
          that.setData({
            recommendGoodsListData: []
          })
        }
      } else {
        wx.showToast({
          title: '查询推荐列表失败：' + res.data.msg,
          icon: 'none'
        })
      }
    }, true)
  },
  goinfo(e) { //为你推荐进入详情
    // wx.navigateTo({
    //   url: '../goodsInfo/goodsInfo?id=' + e.currentTarget.dataset.id,
    // })
    util.navigateTo({
      url: '../goodsInfo/goodsInfo?id=' + e.currentTarget.dataset.id,
    })
  },
  // 校验是否选择规格
  selectSku() {
    var skuselectData = this.data.skuSelectBoxData //选择框选择值
    for (let val of skuselectData) {
      var isCheck = val.specs.find(item => {
        return item.isCheck;
      })
      if (!isCheck) {
        for (let key of val.specs) {
          if (!key.isCheck) {
            return val.key
          }
        }
      }
    }
  },
  selectAttr(e) { //选择属性交互
    var that = this;
    var thisObj = e.currentTarget.dataset.val
    var skuselectData = this.data.skuSelectBoxData //选择框选择值
    for (let val of skuselectData) {
      if (thisObj.attrName == val.key) {
        for (let key of val.specs) {
          if (thisObj.productAttrItemId) {
            if (thisObj.productAttrItemId == key.productAttrItemId && thisObj.productAttributeId == key.productAttributeId) {
              if (key.isCheck) {
                key.isCheck = false
              } else {
                key.isCheck = true
              }
            } else {
              key.isCheck = false
            }
          } else {
            if (thisObj.value == key.value) {
              if (key.isCheck) {
                key.isCheck = false
              } else {
                key.isCheck = true
              }
            } else {
              key.isCheck = false
            }
          }
        }
      }
    }
    that.setData({
      skuSelectBoxData: skuselectData,
    })
    that.matchingSku(skuselectData)
  },
  matchingSku(skuselectData) { //属性匹配Sku
    var that = this;
    var skus = that.data.goodsInfoData.skus //详情返回skulist
    var sceenData = []
    var selectNum = skuselectData.length

    for (let val of skuselectData) {
      for (let val2 of val.specs) {
        if (val2.isCheck) {
          sceenData.push(val2)
        }
      }
    }
    that.setData({
      selectNum: selectNum
    })
    var newSceenData = []
    for (let seSku of sceenData) {
      for (let skO of skus) {
        for (let skv of JSON.parse(skO.skuSpecs)) {
          if (seSku.productAttributeId) {
            if (skv.key == seSku.productAttributeId && skv.value == seSku.productAttrItemId) {
              newSceenData.push(skO.id)
            } else if (seSku.value == skv.value) {
              newSceenData.push(skO.id)
            }
          } else {
            if (seSku.value == skv.value) {
              newSceenData.push(skO.id)
            }
          }

        }
      }
    }
    var selectObj = that.getOneSku(newSceenData)

    if (selectObj.num == selectNum) {
      that.getUpdateGoodInfo(selectObj.skuId)
      that.setData({
        skuId: selectObj.skuId
      })
      that.setData({
        thenSlect: selectObj.num
      })
    } else if (selectObj == selectNum) {
      that.getUpdateGoodInfo(newSceenData[0])
      that.setData({
        skuId: newSceenData[0]
      })
      that.setData({
        thenSlect: selectObj
      })
    }
  },
  getOneSku(slectNum) { //筛选出已选项匹配的Sku
    if (!slectNum) return false;
    if (slectNum.length === 1) return 1;
    let res = {}
    let maxNum = 0;
    let maxValue = null;
    for (let i = 0; i < slectNum.length; i++) {
      let val = slectNum[i]
      res[val] === undefined ? res[val] = 1 : res[val]++;
      if (res[val] > maxNum) {
        maxNum = res[val];
        maxValue = val
      }
    }
    return {
      skuId: maxValue,
      num: maxNum
    }
  },
async  getUpdateGoodInfo(sku) { // 筛选属性刷新商品信息
  console.log('更新商品信息')
    var newSkuId = sku
    var that = this;
    this.getGoodsImgText(newSkuId)
    var parms = {
      // areaCode:headers?headers.provinceCode: wx.getStorageSync('addrCode').provinceCode,
      skuId: sku,
      uuid: that.data.footprintGuid
    }
    let defaultAddr = wx.getStorageSync('addrCode')
    let temporaryAddressData = that.data.temporaryAddressData
    console.log('1请求头参数哈哈temporaryAddressData',temporaryAddressData)
    console.log('1请求头参数哈哈defaultAddr',defaultAddr)
    if(!temporaryAddressData&&!defaultAddr)return
    let province= temporaryAddressData?temporaryAddressData.provinceCode:(defaultAddr&&defaultAddr.provinceCode)
    let city=temporaryAddressData?temporaryAddressData.cityCode:(defaultAddr&&defaultAddr.cityCode)
    let region= temporaryAddressData?temporaryAddressData.regionCode:(defaultAddr&&defaultAddr.districtCode)
    let street= temporaryAddressData?temporaryAddressData.streetCode:(defaultAddr&&defaultAddr.townCode||'')
        let pricePstCode = await this.searchSaleRegion({ province,  city,  region,  street  })
        let headers = {
          "Content-Type": "application/json;charset=UTF-8",
          'token': wx.getStorageSync('loginMsg').token,    //请求token
          'firstAccessServerTime': wx.getStorageSync('firstAccessServerTime'),   //当次打开小程序的时间(小程序完全关闭为一次)
          'pricePstCode':pricePstCode,
          'cityCode':city,
          'provinceCode':province,
          'addrCode':province+','+city+','+region+(street?(','+street):'')
        }
    app.reqFun.requestJson('get', configUrl.getGoodsInfoHead, parms, (res) => {
      console.log('商品信息',res)
      if (res.data.success) {
        var data = res.data.data
        var swiperList = []
        if (data.mainVideo) {
          var videoJson = {
            id: 0,
            type: 'video',
            url: data.mainVideo,
            imgUrl: data.pics[0].picUrl
          }
          swiperList.push(videoJson)
        }
        for (let val of data.pics) {
          val.type = 'image'
          swiperList.push(val)
        }
        var inventoryNum = 0
        for (let sku of data.skus) {
          inventoryNum = sku.inventory + inventoryNum
          if (sku.id == newSkuId) {
            that.setData({
              SelectedSku: sku
            })
            that.setData({
              buyGoodsNum:1
            })
            that.getCoupon(newSkuId) //刷新SKU后获取当前商品优惠
            if (sku.inventory > 0) { //有库存并且有销售区域
              that.getIsGoodsNum(sku) //请求是否有货（未完成）
            } else if (sku.inventory == 0) { //如果没有库存
              that.setData({
                isGoods: '无货'
              })
            }
          }
        }
        that.setData({
          inventoryNum: inventoryNum,
        })
        if (data.type == 2 && data.isSeckill == 1) { //是否参与秒杀活动
          that.getReturnTime(data.endTime)
        }
        if (data.startTime) {
          data.newStartTime = that.formatDate(data.startTime)
        }

        that.setData({
          swiperList: swiperList,
          goodsInfoData: data
        })
      } else {
        wx.showToast({
          title: '获取商品信息失败:' + res.data.msg,
          icon: 'none'
        })
      }
    },'',headers)
  },
  getCarGoodsNumber() { //查询购物车商品数-
    var that = this;
    app.reqFun.requestJson('POST', configUrl.getCarNumber, '', (res) => {
      if (res.data.success) {
        that.setData({
          carGoods: res.data.data
        })
      }
    }, true)
  },
  onChangeBuyNum(e) { //购买商品数量
    this.setData({
      buyGoodsNum: e.detail
    })
  },
  addCar(e) { //添加购物车
    if (this.selectSku()) {
      wx.showToast({
        title: '请选择'+this.selectSku(),
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var skuInfo = e.currentTarget.dataset.sku
    var that = this;
    var goodsInfoData = that.data.goodsInfoData
    var parms = {
      productId: skuInfo.productId,
      productSkuId: skuInfo.id,
      quantity: that.data.buyGoodsNum,
      shopId: goodsInfoData.shopId
    }
    app.reqFun.requestJson('post', configUrl.carAddshop, parms, (res) => {
      if (res.data.success) {
        wx.showToast({
          title: '添加购物车成功',
        })
        that.getCarGoodsNumber()
        that.onCloseModel()
      } else {
        wx.showToast({
          title: '添加商品失败：' + res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  gotoShop() { //在线购买跳转到店体验
    this.setData({
      modelShowType: 2
    })
  },
  goCarBuy() { //详情页进入购物车
    console.log('进购物车')
    let that = this
    app.getLogin((res) => {
      if (res == true) {
        wx.navigateTo({
          url: '../../../packagBuy/pages/carbuy/carbuy',
        })
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })

  },
  bindGetUserInfo: function (e) { //登录-注册
    app.getUserInfo()
    let that = this;
    that.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
    var setFun=setInterval(()=>{
      if(wx.getStorageSync('showGetPhone')){
        that.setData({
          getPhoneNumberData:{
            isShowGetPhoneNumber:true,
          }
        })
        wx.removeStorageSync('showGetPhone')
        clearInterval(setFun)
      }
    },1000)
  },
  onCloseShowGetUserInfo() { //关闭弹出层
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
  gobuyGoods(e) { // 立即购买
    if (this.selectSku()) {
      wx.showToast({
        title: '请选择'+this.selectSku(),
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var goodsNum = this.data.buyGoodsNum
    var sku = e.currentTarget.dataset.val
    var skus = [{
      skuId: sku.id,
      number: goodsNum
    }]
    var submitdata = {
      sku: skus
    }
    submitdata.omsOrderType = 'REGULAR',
      submitdata.settlementMethod = "BUY_NOW"
    wx.setStorageSync('submitSku', submitdata)
    wx.navigateTo({
      url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline',
    })
  },
  // 查询优惠券
  getCoupon(productId) {
    var that = this;
    var parms = {
      productId: productId
    }
    app.reqFun.requestJson('GET', configUrl.productCoupons, parms, (res) => {
      if (res.data.success) {
        that.setData({
          couponListData: res.data.data
        })
      } else {
        wx.showToast({
          title: '获取优惠失败：' + res.data.msg,

        })
      }
    })
  },
  receiveCoupon(e) { //领券
    var that = this;
    var parms = {
      couponId: e.currentTarget.dataset.item.id,
      receivePage: 0,
      receivePlatform: 'mini'
    }
    app.reqFun.requestJson('POST', configUrl.receiveCoupon, parms, (res) => {
      if (res.data.success) {
        wx.showToast({
          title: '领取优惠券成功',
        })
        that.getCoupon(that.data.skuId)
        // that.getCoupon(1106)
      } else {
        wx.showToast({
          title: '领取优惠券失败',
          icon: "none"
        })
      }
    })
  },
  radioChangeShop(e) { //选择门店切换门店
    this.setData({
      selectIndex: e.detail.value
    })

  },
  goIndex(e) {
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  // 立即购买定金-------------------------跳转定金确认订单
  nowBuyDeposit(e) {
    var infoData = this.data.goodsInfoData
    var shop = e.currentTarget.dataset.item //预约门店
    var sku = e.currentTarget.dataset.sku //商品SKU
    console.log('e', e)
    sku.spuPic = infoData.pics[0].picUrl
    sku.spuName = infoData.spuName
    if (infoData.type == 2 && infoData.seckillType == 'theDeposit') {
      sku.showDeposit = infoData.deposit
      sku.spuName = infoData.name
    } else {
      sku.showDeposit = infoData.deposit
    }
    sku.shopName = this.data.goodsInfoData.shopName ? this.data.goodsInfoData.shopName : null
    sku.orderType = ((infoData.seckillType == 'theDeposit' && infoData.type == 2) ? 'SECONDS_KILL_DEPOSIT' : 'STORE_DEPOSIT')
    wx.setStorageSync('nowBuyDepositShop', shop)
    wx.setStorageSync('nowBuyDepositSku', sku)
    var userId = wx.getStorageSync('loginMsg').userId.toString()
    var timestamp = Date.parse(new Date()).toString()
    //定金下单的uuid为用户id拼接时间戳
    wx.setStorageSync('submitUUID', userId + timestamp)
    wx.navigateTo({
      url: '../../../packagBuy/pages/confirmOrder/confirmOrder?type=deposit',
    })
  },
  reminBtnFun(e) { //提醒
    let activityId = e.currentTarget.dataset.activityId
    let activityType = e.currentTarget.dataset.activityType
    let skuId = e.currentTarget.dataset.skuId
    let that = this
    // 活动开始提醒
    let tempIds = []
    let activityStart = app.globalData.msgTemplateMap['activityStart']
    let activityStartTempId = activityStart.msgTemplateId
    tempIds.push(activityStartTempId)
    wx.requestSubscribeMessage({
      tmplIds: tempIds,
      success(res) {
        if (res[activityStartTempId] == "accept") {
          that.appointmentReminder(activityType, activityId, skuId)
        } else {
          console.log('失败')
        }
      },
      fail(res) {
        console.log('订阅出错', res)
        wx.showToast({
          title: '订阅消息发送失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  appointmentReminder(activityType, activityId, skuId) {
    var sku = this.data.SelectedSku
    let params = {
      activityType: activityType,
      activityId: activityId,
      skuId: skuId,
      userOpId: wx.getStorageSync('loginMsg').openid
    }
    app.reqFun.requestJson('POST', configUrl.addSubscribe, params, (res) => {
      if (res.data.success) {
        wx.showToast({
          title: '提醒成功',
          icon: 'success',
          duration: 2000
        })
        sku.isRemin = true
        this.setData({
          SelectedSku: sku
        })
      }
    })
  },
  goSearchCoupon(e) { //优惠券跳转
    var info = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `../shopSearch/shopSearch?couponId=${info.id}&from=coupon`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (e) {

  },
  // 根据用户ID获取所属门店
  getShareShops(user){
    return new Promise((resolve,reject)=>{
      app.reqFun.requestJson('get',configUrl.recommendShop+'/'+user,{},(res)=>{
        if(res.data.success==1&&res.data.data.length>0){
          resolve (res.data.data)
        }else{
          resolve ([])
        }
      })
  })
   },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow () {
// 导购分享则显示推荐门店
setTimeout(()=>{
  this.setData({
    partnerInfo:getApp().globalData.partnerInfo
  })
  },500)

  setTimeout(()=>{
const  shareUserId=getApp().globalData.shareUserId
if (shareUserId) {
  app.reqFun.requestJson('get',configUrl.recommendShop+'/'+shareUserId,{},(res)=>{
    if(res.data.success==1&&res.data.data.length>0){
        this.setData({
          recomandShop: res.data.data[0],
          showRecomandShop:true
        })
    }else{
     this.setData({
      showRecomandShop:false
    })
    }
  })
  }
  },500)


  //拿到服务器时间
  var serverLocalDate = new Date().getTime();
  //调用函数开始计时
  this.serverLocalDate(serverLocalDate);
  if (this.data.reGuid) {
    //第二次onshow时重新生成guid
    this.setData({
      footprintGuid: util.guid()
    })
  } else {
    //第一次onshow
    this.setData({
      reGuid: true
    })
  }
},
//服务器系统时间开始计时
serverLocalDate: function (serverLocalDate) {
  console.log(serverLocalDate)
  var _this = this;
  let newDate = serverLocalDate;
  _this.setData({
    servicetimeInterval: setInterval(function () { // 循环执行  
      newDate = (newDate / 1000 + 1) * 1000;
      _this.setData({
        systimestamp: newDate
      })
    }, 1000)  // 每秒执行一次以达到更新时间的目的
  })
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that=this
    var skuid = that.data.skuId //商品id
    console.log('skuid', skuid)
    var userId = wx.getStorageSync('loginMsg').userId
    var goodsInfo = this.data.goodsInfoData
    let path = `/packageShop/pages/goodsInfo/goodsInfo`
    let query = `?userId=${userId}&skuId=${skuid}&hid=${wx.getStorageSync('loginMsg').userId}`
    that.onCloseModel()
    //保存分享记录
    app.insertShareRecord(path, query, skuid, 'goodsInfo', userId)
    return {
      title: goodsInfo.name,
      path: path + query
    }
  },
  selectInfoMsg: function (e) { //tab切换查看商品信息
    var msgType = e.currentTarget.dataset.val
    if (msgType == 1) {
      this.setData({
        toView: 'shopInfo',
        fontText: 1
      });
    } else if (msgType == 2) {
      this.setData({
        toView: 'evalInfo',
        fontText: 2
      });
    } else {
      this.setData({
        toView: 'igmgTextInfo',
        fontText: 3
      });
    }
  },
  getScroll(e) { //监听滑动
    var scorll = e.detail.scrollTop
    if (scorll > 50 && scorll < 150) {
      this.setData({
        headerClass: 'headerClass1',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo'
      });
    } else if (scorll > 150) {
      this.setData({
        headerClass: 'headerClass2',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo',
      });
    } else if (scorll < 50) {
      this.setData({
        headerClass: 'headerClass3',
        tableIsHidden: true,
        returnBoxgo: '',
      });
    }
    if (scorll < 500) {
      this.setData({
        fontText: 1
      });
    } else if (scorll > 500 && scorll < 1100) {
      this.setData({
        fontText: 2
      });
    } else {
      this.setData({
        fontText: 3
      });
    }
  },
  selectModel(e,open,spellId,popup,val) { //打开弹窗
    let that = this
    if (e) {
      var open = e.currentTarget.dataset.open
      if (e.currentTarget.dataset.spells) {
        var spellId = e.currentTarget.dataset.spells.id
      }
      if (spellId) {
        that.setData({
          spellGroupId: spellId
        })
      }
      that.setData({
        popupOpen:open
      })
    }
    if (open) {
      that.setData({
        popupOpen:open
      })
    }
    if (spellId) {
      that.setData({
        spellGroupId:spellId
      })
    }

    
    app.getLogin((re)=>{
      if(re){
        if (e) {
          if (e.currentTarget.dataset.popup == "buy-Experience") {
            that.setData({
              modelShowType: e.currentTarget.dataset.val
            })
          }
          if (e.currentTarget.dataset.popup == "buy-Separately") {
            that.setData({
              modelShowType: e.currentTarget.dataset.val
            })
          }
          if (e.currentTarget.dataset.popup == "shear-pop-download") {
            var page = 'Page'
            app.reqFun.requestJson("POST", configUrl.QRCode)
          }
          that.setData({
            showOtherAddr: false,
            modelPopup: e.currentTarget.dataset.popup
          })
        }
        if (val) {
          that.setData({
            modelShowType: val
          })
        }
        if (popup) {
          that.setData({
            showOtherAddr: false,
            modelPopup: popup
          })
        }
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          } else {
            callback(true)  //低版本微信绑过电话视为已登录
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
  // 单独购买
  buySeparately() {
    // this.setData({
    //   modelPopup: 'buy-Separately'
    // })
  },
  downloadModal: function (e) { //打开分享海报弹窗
    var that = this;
    var skuid = that.data.skuId //商品id
    var userId = wx.getStorageSync('loginMsg').userId
    let path = `packageShop/pages/goodsInfo/goodsInfo`
    var parms = {
      page: path,
      scene: JSON.stringify({
        userId: userId,
        skuId: skuid
      })
    }
    //保存分享记录
    app.insertShareRecord(path, '', skuid, 'goodsInfo', userId)
    that.downLoadCode(parms)
  },
  downLoadCode(parms) { //生成分享二维码
    var that = this;
    var goodsImg = ''
    if (that.data.goodsInfoData.picture) {
      goodsImg = that.data.goodsInfoData.picture
    } else {
      for (let val of that.data.goodsInfoData.pics) {
        if (val.mainPicFlag == "Y") {
          goodsImg = val.picUrl
        }
      }
    }
    var goodsImgUrl = util.getImgUrl(goodsImg)
    wx.getImageInfo({
      src: goodsImgUrl,
      success: function (res) {
        that.setData({
          goodsImgUrl: res.path
        })
        getImgFromSize(goodsImgUrl, 300, 230).then((res)=>{
          // 在res中返回结果：res.maxWidth, res.maxHeight, res.dx, res.dy
         console.log(res)
         that.setData({
           imgInfoWH:res
         })
        })
      }
    })
    app.reqFun.requestJson('POST', configUrl.QRCode, parms, (res) => {
      if (res.data.success) {
        that.setData({
          shearImg: 'data:image/png;base64,' + res.data.data,
          modelPopup: 'shear-pop-download'
        })
        that.send_code('data:image/png;base64,' + res.data.data)
        console.log('shearImg', that.data.shearImg)
      }
    })
    var getPartnerInfos=wx.getStorageSync('loginMsg')
    if(getPartnerInfos.partner && getPartnerInfos.partnerInfo){
      that.setData({
        shareMSG:getPartnerInfos.partnerInfo,
      })
      var imgurlpart=util.getImgUrl(getPartnerInfos.partnerInfo.partnerPhoto)
      wx.getImageInfo({
        src:  imgurlpart,
        success: function (res) {
          that.setData({
            partnerHead: res.path
          })
        }
      })
    }else{
      app.reqFun.requestJson('GET',configUrl.centerCount,'',(res)=>{
        if(res.data.success) {
          var userInfo=res.data.data.userInfo
          userInfo.icon=util.getImgUrl(userInfo.icon)
          that.setData({
            userInfo:userInfo,
          })
          var json={
            partnerNickName:userInfo.nickname,
            partnerPhone:userInfo.phone?userInfo.phone:'',
            partnerPhoto:userInfo.icon
          }
          that.setData({
            shareMSG:json
          })
          // 用户头像
          wx.getImageInfo({
            src:  userInfo.icon,
            success: function (res) {
              that.setData({
                UserheadImg: res.path
              })
            }
          })
        }
      })

    }
  },
  send_code(code) { //base64图片转本地缓存图片
    var that = this;
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: code.slice(22),
      encoding: 'base64',
      success: () => {
        //写入成功了的话，新的图片路径就能用了
        that.setData({
          codeImg: codeimg
        })
      }
    });
  },
  collenGoods(e) { //商品收藏
    var that = this;
    var id = this.data.skuId;
    var goodInfo = this.data.goodsInfoData
    if (goodInfo.isCollection) {
      app.reqFun.requestJson('GET', configUrl.deleteProduct, {
        skuIds: id
      }, (res) => {
        if (res.data.success ) {
          goodInfo.isCollection = false
          that.setData({
            goodsInfoData: goodInfo
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    } else {
      app.reqFun.requestJson('GET', configUrl.collectionProduct, {
        skuId: id
      }, (res) => {
        if (res.data.success ) {
          wx.showToast({
            title: '收藏成功',
          })
          goodInfo.isCollection = true

          that.setData({
            goodsInfoData: goodInfo
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    }

  },
  onCloseModel(e) { //关闭弹窗
    this.setData({
      modelPopup: ''
    })
  },
  banspew(e) { //禁止页面内弹出层滑动
    return;
  },
  gotoOnlineBuy(e) { //到店体验返回在线购买
    this.setData({
      modelShowType: 1
    })
  },
  goSelsctShop(e) { //到店体验-选择门店
    var that = this;
    this.setData({
      modelPopup: 'store'
    })
    var isDefaultLocation = wx.getStorageSync('addrCode')
    var temporaryAddressData = that.data.temporaryAddressData
    if (temporaryAddressData&&temporaryAddressData.provinceCode) {
      var address = temporaryAddressData.province + temporaryAddressData.cit + temporaryAddressData.region
      if (temporaryAddressData.street) {
        address += temporaryAddressData.street
      }
      that.getnearby(address)
    } else {
      var address = isDefaultLocation.province + isDefaultLocation.city + isDefaultLocation.district + isDefaultLocation.townName
      that.getnearby(address+isDefaultLocation.street+isDefaultLocation.streetNumber)
      that.setData({
        goShopAddr: address
      })
    }
  },
  // 拼单
  placeOrder() {
    let that = this
    var goodsNum = that.data.buyGoodsNum
    var sku = that.data.SelectedSku
    // if (sku.limitNum && sku.inventory>sku.limitNum) {
    //   goodsNum = sku.limitNum
    // }
    var skus = [{
      skuId: sku.id,
      number: goodsNum
    }]
    var submitdata = {
      sku: skus
    }
    submitdata.omsOrderType = 'SPELL_BUY',
    submitdata.settlementMethod = "BUY_NOW"
    submitdata.groupActivityId = that.data.goodsInfoData.groupActivityId
    if (that.data.spellGroupId) {
      submitdata.groupId = that.data.spellGroupId
    }
    wx.setStorageSync('submitSku', submitdata)
    wx.navigateTo({
      url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline',
    })
    that.setData({
      spellVerDlg: false
    })
  },
  // 去拼单校验
goSpell(data) {
  if (this.selectSku()) {
    wx.showToast({
      title: '请选择'+this.selectSku(),
      icon: 'none',
      duration: 2000
    })
    return;
  }
  let that = this
  let spuId = data.currentTarget.dataset.data.spuId
  let groupActivityId = data.currentTarget.dataset.data.groupActivityId
  let join = data.currentTarget.dataset.type
  that.setData({
    modelPopup: ''
  })
  if (join) {
    that.placeOrder()
  } else {
    let checkSpellBuyUrl = spellApi.checkSpellBuy + '?groupActivityId=' + groupActivityId + '&spuId=' + spuId
    app.reqFun.requestJson('get', checkSpellBuyUrl, '', (res) => {
      if (res.data.success ) {
        if (res.data.data.num == 0) {
          that.placeOrder()
        } else if(res.data.data.num == 1) {
          let list = res.data.data.list
          that.setData({
            spellList: list,
            spellVerDlg: true,
            spellFailed: false
          })
          let spellList = that.data.spellList
          if (spellList && spellList.length >0) {
            that.setData({
              spellGroupId: spellList[0].id
            })
          }
        } else if(res.data.data.num == 2) {
          that.setData({
            spellVerDlg: true,
            spellFailed: true
          })
        } 
      }
    })
  }
},
onClose() {
  this.setData({
    spellVerDlg: false
  })
},
// 一键拼单
oneClickOrder() {
  if (this.selectSku()) {
    wx.showToast({
      title: '请选择'+this.selectSku(),
      icon: 'none',
      duration: 2000
    })
    return;
  }
  this.placeOrder()
},
// 发起砍价
cutPricefun(data) {
  if (this.selectSku()) {
    wx.showToast({
      title: '请选择'+this.selectSku(),
      icon: 'none',
      duration: 2000
    })
    return;
  }
  let that = this
  let skuId = data.currentTarget.dataset.skuid
  let groupActivityId = data.currentTarget.dataset.data.groupActivityId
  let buyGoodsNum = that.data.buyGoodsNum
  let parms = {
    "buyNum": buyGoodsNum,
    "groupActivityId": groupActivityId,
    "skuId": skuId
  }
  app.reqFun.requestJson('post', spellApi.launchCutPrice, parms, (res) => {
    if (res.data.success) {
      let data = res.data.data
      wx.navigateTo({
        url: '/packageLive/pages/cutPrice/detail/detail?data=' + JSON.stringify(data) + '&id=' + data.cutPriceGroupId,
      })
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
    }
  }, true)
},
  goPlayVideo(e) { //开始播放视频
    var that = this;
    var videoplay = wx.createVideoContext('video')
    wx.getNetworkType({ // 获取网络类型
      success: function (res) {
        if (res.networkType != 'wifi') {
          that.setData({
            showNotWifiPaly: true
          })
          setTimeout(function () {
            that.setData({
              showNotWifiPaly: false
            })
          }, 1500)
        }
      }
    })
    videoplay.play()
    that.setData({
      swiperTyle: false,
      PlayTyle: true
    })


  },
  palyEndLitten(e) { //监听播放完
    this.setData({
      PlayTyle: false
    })
  },
  stopPalyVideo(e) {
    var videoplay = wx.createVideoContext('video')
    videoplay.pause()
  },
  handleContact(e) {
  },
  //分享商品海报
  downloadCanvas: function (e) {
    let that = this
    app.getLogin((re)=>{
      if(re){
        that.setData({
          modelPopup: ''
        })
        wx.showLoading({
          title: '图片生成中···',
        })
        var userInfo=that.data.userInfo
        var goodsInfo = that.data.goodsInfoData
        var codeImg = that.data.codeImg
        var goodsImgUrl = that.data.goodsImgUrl
        const ctx = wx.createCanvasContext('shareGoods');
        var logInfo=wx.getStorageSync('loginMsg')
        var headerImgUser ,headerNameUser ,headerPhoneUser
        if(logInfo.partner && logInfo.partnerInfo){
          headerImgUser=that.data.partnerHead
          headerNameUser=logInfo.partnerInfo.partnerNickName
          headerPhoneUser=logInfo.partnerInfo.partnerPhone
        }else{
          headerImgUser=that.data.UserheadImg
          headerNameUser=userInfo.nickname
          headerPhoneUser=userInfo.phone?userInfo.phone:''
        }
        ctx.save();
        ctx.beginPath()     //头像绘制
        ctx.setFillStyle('#fff')
        ctx.fillRect(0, 0, 300, 60)
        ctx.arc(30, 25, 20, 0, 2*Math.PI)
        ctx.clip()
        ctx.drawImage(headerImgUser, 10, 5, 40, 40)
        ctx.restore()
        ctx.beginPath()
        ctx.setFillStyle('#333')
        ctx.font = "bold 13px Arial";
        var nickNameWidth = ctx.measureText(headerNameUser).width
        ctx.fillText(headerNameUser, 65,20, nickNameWidth)
        ctx.fillText(headerPhoneUser,65+nickNameWidth+20,20)
        ctx.setFillStyle('#888')
        ctx.font = "200 13px Arial";
        ctx.fillText('给您分享此商品',65,40)

        ctx.beginPath() //开始
        ctx.drawImage(goodsImgUrl,0, 60, 300, 300)
        ctx.restore()

        ctx.beginPath() //开始绘制描述部分
        ctx.setFillStyle('#fff')
        ctx.fillRect(0, 300+70, 300, 140)
        ctx.font = "bold 16px Arial";
        ctx.setFillStyle('#333')
        var name = goodsInfo.spuName //插入商品名称
        var txtWidth = ctx.measureText(name).width
        var textToHeight = 390
        if (txtWidth < 190) {
          ctx.fillText(name, 10, textToHeight + 5)
          textToHeight = textToHeight + 20
        } else { //处理插入商品名称过长
          var row = []
          var n = Math.ceil(185 / 16)
          for (var i = 0, l = name.length; i < l / n; i++) {
            var a = name.slice(n * i, n * (i + 1));
            row.push(a);
          }
          for (var b = 0; b < row.length; b++) {
            ctx.fillText(row[b], 10, textToHeight)
            textToHeight = textToHeight + 20
          }
        }
        ctx.beginPath() //绘制标签
        ctx.lineWidth = "1";
        ctx.strokeStyle = "#F15643";
        ctx.font = "bold 10px Arial";
        if (goodsInfo.deposit && goodsInfo.deposit != goodsInfo.deduction) {
          var tags = `定金${goodsInfo.deposit}元到店可抵${goodsInfo.deduction}元`
          var width = ctx.measureText(tags).width
          ctx.rect(10, textToHeight, width + 10, 13)
          ctx.stroke();
          ctx.beginPath()
          ctx.setFillStyle('#F15643')
          ctx.fillText(tags, 13, textToHeight + 10)
        } else if (goodsInfo.deposit && goodsInfo.deposit == goodsInfo.deduction) {
          var tags = `定金${goodsInfo.deposit}元`
          var width = ctx.measureText(tags).width
          ctx.rect(10, textToHeight, width + 5, 13)
          ctx.stroke();
          ctx.beginPath()
          ctx.setFillStyle('#F15643')
          ctx.fillText(tags, 13, textToHeight + 10)
        }
        var labes = 10
        var namewid = 13
        if (goodsInfo.labels) {
          if (that.data.couponListData.length > 0) {
            goodsInfo.labels.push({
              id: null,
              labelName: '券'
            })
          }
          for (let val of goodsInfo.labels) {
            var name = val.labelName
            var labelNameWidth = ctx.measureText(name).width
            ctx.setFillStyle('#F15643')
            ctx.rect(labes, textToHeight + 20, labelNameWidth + 5, 13)
            ctx.fillText(name, namewid, textToHeight + 30)
            namewid = (labelNameWidth + namewid + 5 + 10)
            labes = (labelNameWidth + 5 + labes + 10)
            ctx.setFillStyle('#F15643')
            ctx.stroke();
          }
        }
        ctx.beginPath() //绘制二维码
        ctx.drawImage(codeImg, 200, 380, 90, 90)
        ctx.font = "bold 12px Arial";
        ctx.setFillStyle('#888')
        ctx.fillText('长按/扫描识别', 210, 490)
        ctx.draw()
        setTimeout(function () {
          wx.canvasToTempFilePath({ //canvas生成图片
            x: 0,
            y: 0,
            width: 300,
            height: 520,
            canvasId: 'shareGoods',
            success(res) {
              console.log(res.tempFilePath)
              wx.saveImageToPhotosAlbum({     //保存图片到相册
                filePath:res.tempFilePath,
                success:function(e){
                  wx.hideLoading({})
                  wx.showToast({
                    title: '保存图片成功',
                    duration:3000
                  })
                },fail:function(e){
                  wx.hideLoading({})
                  wx.showModal({
                    title: '保存失败',
                    content: '保存图片失败,请点击右上角按钮-设置-开启授权',
                    showCancel:false,
                  })
                }
              })
            }
          })
        }, 4000)
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          } else {
            callback(true)  //低版本微信绑过电话视为已登录
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
  //展开合伙人信息
  showPartnerAll: function () {
    this.setData({
      isShowPartnerAll: !this.data.isShowPartnerAll,
    })
  },
  //展示合伙人二维码
    partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  },
  /**绑定手机号 ---start*/
  closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false

      }
    })
  },
  getPhoneNumber(e){
    var that=this;
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',configUrl.decryptGetPhone,option,(res)=>{
        if(res.data.success){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false,
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
        }
      })
    } else {
      console.log('取消')
    }
  }
  /**绑定手机号 ---end*/
})

// 获取图片的 w，h
function getImgInfo(src,callback){
  wx.getImageInfo({
    src: src,
    success(res){
      console.log(res)
      callback&&callback(res)
      return res
    }
  })
}

// 获取能在图片中按对应比例能够截取的最大尺寸
// 传入图片地址和需要展示的尺寸
function getImgFromSize(src, w, h){
  return new Promise((resolve, reject)=>{
    let size = {}
    getImgInfo(src, (res) => {
      const imgW = res.width
      const imgH = res.height
      console.log(imgW, imgH)
      let maxWidth = ''
      let maxHeight = ''
      let dx = ''
      let dy = ''
      if ((imgW / imgH) > (w / h)) {
        // 在比例上，原始图片的宽度多出
        // 所以根据较短的一边来计算，按照高度imgH来计算最终截取尺寸
        maxWidth = imgH / h * w
        maxHeight = imgH
        dx = (imgW - maxWidth) / 2
        dy = 0
      } else {
        // 在比例上，原始图片的高度多出
        // 所以根据较短的一边来计算，按照宽度imgW来计算最终截取尺寸
        maxWidth = imgW
        maxHeight = imgW / w * h
        dx = 0
        dy = (imgH - maxHeight) / 2
      }
      resolve({
        maxWidth,
        maxHeight,
        dx,
        dy
      })
    })
  })
}